<?php
/**资料管理
 * Created by leiying
 * Date: 2018-06-05
 * Time: 14:30:21
 */

namespace Admin\Controller;


class DataController extends AdminController
{
    /**列表
     * @author leiying
     */
    public function DataList(){
        $limit = LIMIT;
        $get = I('post.');

        $search_data = array();//筛选数据
        $where = array();//条件

        if(IS_POST){
            session('searchdata_DataList',$get);
        }else{
            if(empty(I('get.p'))){
                session('searchdata_DataList',null);
            }
            $get = $search_data = session('searchdata_DataList');
        }
        //搜索条件：项目分类
        if(isset($get['p_id']) && $get['p_id'] != ''){
            $search_data['p_id'] = trim($get['p_id']);
            $where['a.p_id'] = array('like','%'.$search_data['p_id'].'%');
        }
        //搜索条件：资料名称
        if(isset($get['name']) && $get['name'] != ''){
            $search_data['name'] = trim($get['name']);
            $where['a.name'] = array('like','%'.$search_data['name'].'%');
        }
        $count = M('data')->alias("a")->where($where)->count();

        $Page = new  \Think\Page($count, $limit);// 实例化分页类 传入总记录数
        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('last', '末页');
        $Page->setConfig('first', '首页');
        $Page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出

        //处理排序逻辑(默认主键倒序)
        $sort = array(
            'field'=>I('get.sort_field','id'),
            'type'=>I('get.sort_type','desc'),
        );
        $sortString = 'a.'.$sort['field'] . ' ' .$sort['type'];
        $this->assign('sort',$sort);

        $lists = M('data')
            ->alias("a")
            ->field("a.*,b.nickname,c.name project_name")
            ->join(C('DB_PREFIX')."member b ON a.admin_uid = b.uid","left")
            ->join(C('DB_PREFIX')."project c ON a.p_id = c.id","left")
            ->where($where)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order($sortString)
            ->select();
        $this->assign('lists',$lists);
        $this->assign('searchs',$search_data);

        $projects = M('project')->order("add_time desc")->select();
        $this->assign("projects",$projects);
        $p = I('get.p',"1");
        $this->assign("p",$p);

        $this->display();
    }


    /**批量操作
     * @param null $method
     * @author leiying
     */
    public function changeStatus($method=null){
        $id = I('post.id');
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        switch ( strtolower($method) ){
            case 'deletegroup':
                $delete_path = M('data')->where(array("id"=>$id))->getField("path");
                $res = M("data")->where(array("id"=>array('in',$id)))->delete();
                if($res){
                    if(isset($delete_path)){
                        @unlink($_SERVER['DOCUMENT_ROOT'].$delete_path);
                    }
                    $this->success("删除成功");
                }else{
                    $this->error("删除失败");
                }
                break;
            default:
                $this->error($method.'参数非法');
        }
    }

    /**添加
     * @author leiying
     */
    public function DataAdd(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            $post = I('post.');
            /*处理参数(请根据业务逻辑适当修改)*/
            //项目分类
            $p_id = trim($post['p_id']);
            if(empty($p_id)){
                $this->error("项目分类不能为空");
            }

            //路径
            $path = trim($post['uploadupfile']);
            if(empty($path)){
                $this->error("请先选择资料上传");
            }

            if($_FILES){
                $path = "/Uploads/Data/" . date("Y-m-d") . "/";
                $path = $this->upload_file($_FILES,$path);
            }else{
                $this->error("请先选择资料上传");
            }

            //资料名称
            /*获取文件名字和后缀*/
            $file_info=pathinfo($_FILES["upfile"]["name"]);
            $ext = $file_info["extension"];
            $name = $file_info["filename"];
            if(!empty($post['name'])){
                $name = trim($post['name']);
            }

            $data = array(
                'p_id' => $p_id,
                'name' => $name,
                'ext' => $ext,
                'path' => $path,
                'admin_uid' => UID,
                'add_time' => time(),
            );

            $res = M("data")->add($data);
            if($res){
                $this->success("添加成功");
            }else{
                $this->error("添加失败");
            }
        }else{
            $projects = M('project')->order("add_time desc")->select();
            $this->assign("projects",$projects);
            $this->display();
        }
    }

    /**编辑
     * @author leiying
     */
    public function DataEdit(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            $post = I('post.');
            $id = $post['id'];
            if(empty($id)){
                $this->error('请选择需要操作的数据');
            }
            /*处理参数(请根据业务逻辑适当修改)*/
            //项目分类
            $p_id = trim($post['p_id']);
            if(empty($p_id)){
                $this->error("项目分类不能为空");
            }

            if($_FILES){
                $path = "/Uploads/Data/" . date("Y-m-d") . "/";
                $path = $this->upload_file($_FILES,$path);
                /*获取文件名字和后缀*/
                $file_info=pathinfo($_FILES["upfile"]["name"]);
                $ext = $file_info["extension"];
                $name = $file_info["filename"];
                if(!empty($post['name'])){
                    $name = trim($post['name']);
                }
                $delete_path = M('data')->where(array("id"=>$id))->getField("path");
            }else{
                if(isset($post['path']) && !empty($post['path'])){
                    $path = $post['path'];
                    $file_info = pathinfo($path);
                    $ext = $file_info["extension"];
                    $name = $file_info["filename"];
                    if(!empty($post['name'])){
                        $name = trim($post['name']);
                    }
                }else{
                    $this->error("请先选择资料上传");
                }
            }
            $data = array(
                'p_id' => $p_id,
                'name' => $name,
                'ext' => $ext,
                'path' => $path,
                'admin_uid' => UID,
                'add_time' => time(),
            );

            $res = M('data')->where(array("id"=>$id))->save($data);
            if(is_numeric($res)){
                if(isset($delete_path)){
                    @unlink($_SERVER['DOCUMENT_ROOT'].$delete_path);
                }
                $this->success('编辑成功');
            }else{
                $this->error('编辑失败');
            }
        }else{
            $id = I('get.id');
            if(empty($id)){
                $this->error("请选择需要操作的数据");
            }
            $res = M('data')->where(array('id'=>$id))->find();
            $this->assign('res',$res);
            $projects = M('project')->order("add_time desc")->select();
            $this->assign("projects",$projects);
            $p = I('get.p',"1");
            $this->assign('p',$p);
            $this->display();
        }
    }

    /**下载资源
     * @author leiying
     */
    public function download(){
        $method = I('method','data');
        $id = I('id',0);
        switch($method){
            case 'data':
                $res = M("data")->field("path,name,ext")->where(array("id"=>$id))->find();
                $path = isset($res['path'])?$res['path']:'';
                $name = isset($res['name'])?$res['name']:'';
                $ext = isset($res['ext'])?$res['ext']:'';
                break;
            case 'apply':
                $res = M("apply")->field("path,number name")->where(array("id"=>$id))->find();
                $path = isset($res['path'])?$res['path']:'';
                $name = isset($res['name'])?$res['name']:'';
                $ext = pathinfo($path)["extension"];
                break;
            default;
                $this->error("参数错误，请联系开发人员");
                break;
        }
        download_file($path,$name.'.'.$ext);
    }

    /**上传资源文件
     * @param $files
     * @param $path  尾部加上"/"
     * @return string  返回存入数据表的路径
     * @author leiying
     */
    protected function upload_file($files,$path,$file_name = 'upfile'){
        $uptypes=array(//word excel pdf jpg png rar zip
            'application/vnd.ms-excel',//xls
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',//xlsx
            'application/msword',//doc
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',//docx
            'application/x-zip-compressed',//zip
            'application/octet-stream',//rar
            'application/pdf',//pdf
            'image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png'
        );//上传文件类型列表
        $max_file_size = 200*1024*1024;     //上传文件大小限制, 单位BYTE
        $destination_folder=$_SERVER['DOCUMENT_ROOT'].$path; //上传文件路径
        if (!is_uploaded_file($files[$file_name]["tmp_name"])){   //防止脚本欺骗
            $this->error('图片不存在');
        }

        $file = $files["upfile"];
        if($max_file_size < $file["size"]){   //检查文件大小
            $this->error('文件太大');
        }

        if(!in_array($file["type"], $uptypes)){   //检查文件类型
            $this->error("文件类型不符!".$file["type"]);
        }

        if(!file_exists($destination_folder))
        {
            mkdir($destination_folder,0777,true);
        }

        $filename=$file["tmp_name"];
//        $image_size = getimagesize($filename);
        $pinfo=pathinfo($file["name"]);
        $ftype=$pinfo['extension'];
        $destination = $destination_folder.md5(time().mt_rand(1000, 9999)).".".$ftype;
        if (file_exists($destination))
        {
            $this->error("同名文件已经存在了");
        }

        if(!move_uploaded_file ($filename, $destination))
        {
            $this->error($filename."移动到".$destination."出错");
        }

        $pinfo=pathinfo($destination);
        $fname=$pinfo["basename"];
        return $path.$fname;
    }


}